package servlet.user;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entities.User;
import managers.EntityManagerAux;

/**
 * Servlet implementation class SendMessage. Classe en charge de
 * sauvegarder les messages des utisateurs dans la base de donnes
 */
public class SendMessage extends HttpServlet {
        private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SendMessage() {
        super();
        // TODO Auto-generated constructor stub
    }

        /**
         * On lit la requete, avec les paramettres et on appele aux manager
         * pour sauvegarder le message envoye
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
    @EJB EntityManagerAux mng;
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                // TODO Auto-generated method stub
        	    String user = (String)request.getSession().getAttribute("id");
        	    System.out.println("User is: "+user);
			
                String recipient = request.getParameter("Destinataire");
                String header = request.getParameter("Header");
                String message = request.getParameter("Message");
               
                if(!recipient.isEmpty() && !header.isEmpty() && !message.isEmpty()) {
                        mng.sendMessage(recipient, header, message, user);
                        String goTo="close.jsp";
                        request.getRequestDispatcher(goTo).forward(request, response);
                        
                }else {
                        String goTo="Error.jsp";
                        request.getRequestDispatcher(goTo).forward(request, response);
                }
        }

        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                // TODO Auto-generated method stub
                doGet(request,response);
        }

}
